package com.example.jdbc.c3p0;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.junit.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @program: sms
 * @description:
 * @author: zhanghz001
 * @create: 2020-11-09 16:11
 **/
public class C3P0Demo01 {
    @Test
    public void test03() throws Exception {
        //
        // 自定义C3P0工具类，要求如下
        //
        // 1.创建私有静态数据源(连接池对象)成员变量
        //
        // 2.创建公有的得到数据源(连接池对象)的方法
        System.out.println(C3P0DataSourceUtils.getDataSource());
        //
        // 3.创建共有的得到连接对象的方法
        System.out.println(C3P0DataSourceUtils.getConnection());

    }

    @Test
    public void test02() throws Exception {

        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        for (int i = 0; i < 11; i++) {

            Connection connection = dataSource.getConnection();
            System.out.println(i + " : " + connection);
            if (i == 5) {
                //wrapping: com.mysql.jdbc.JDBC4Connection@78c03f1f 看到两次,说明复用了
                //5 : com.mchange.v2.c3p0.impl.NewProxyConnection@5ce81285 [wrapping: com.mysql.jdbc.JDBC4Connection@78c03f1f]
                connection.close();
            }
        }

    }

    @Test
    public void test01() throws Exception {
        //    c3p0创建连接对象
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        Connection connection = dataSource.getConnection();

        String sql = "select * from student ";
        PreparedStatement ps = connection.prepareStatement(sql);
        ResultSet rs = ps.executeQuery();
        while (rs.next()) {
            System.out.println(rs.getInt("sid") + "\t" +
                    rs.getString("name") + "\t" + rs.getInt("age") + "\t" +
                    rs.getDate("birthday"));
        }
        rs.close();
        ps.close();
        connection.close();
    }
}
